package com.demo.springbooot_demo.service;


import com.demo.springbooot_demo.pojo.LoginUser;
import com.demo.springbooot_demo.pojo.ResponseMessage;
import com.demo.springbooot_demo.pojo.User;
import com.demo.springbooot_demo.pojo.dto.LoginUserDto;
import com.demo.springbooot_demo.pojo.dto.UserDto;
import com.demo.springbooot_demo.repository.UserRepository;
import com.demo.springbooot_demo.utils.RedisCache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.demo.springbooot_demo.utils.TokenManager;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
public class UserService implements IUserService {
    @Autowired
    UserRepository userRepository;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PasswordEncoder passwordEncoder ;

    @Autowired
    private AuthenticationManager authenticationManager ;

    @Override
    public User add(UserDto user){
        User userPojo=new User();
        BeanUtils.copyProperties(user,userPojo);
        return userRepository.save(userPojo);

    }

    @Override
    public User getUser(Integer userId) {
        return userRepository.findById(userId).<IllegalArgumentException>orElseThrow(() -> {
            throw new IllegalArgumentException("用户不存在，参数异常!");
        });
    }

    @Override
    public User edit(UserDto user){
        User userPojo=new User();

        //密码加密
        String pwd = userPojo.getPassword();
        String encode = passwordEncoder.encode(pwd);
        userPojo.setPassword(encode);
        BeanUtils.copyProperties(user,userPojo);
        return userRepository.save(userPojo);

    }

    @Override
    public void delete(Integer userId) {
        userRepository.deleteById(userId);
    }

    
    @Override
    public User findByUserName(String username) {
        System.out.println(username);
        return userRepository.findByUserName(username).<IllegalArgumentException>orElseThrow(() -> {
            throw new IllegalArgumentException("用户名不存在，参数异常!");
        });
    }

    /**
     * 登陆服务
     * @param user
     * @return
     */
    @Override
    public ResponseMessage login(LoginUserDto user) {
        //AuthenticationManager.authenticate 用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证没通过提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登陆失败");
        }
        //通过认证返回jwt token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getUserId().toString();
        String token = TokenManager.createToken(userid);
        //userid key 存入缓存
        redisCache.setCacheObject("demo-user:"+userid,loginUser);
        //返回token
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        return ResponseMessage.success(map);
    }

    @Override
    public ResponseMessage logout() {
        //获取userid
       UsernamePasswordAuthenticationToken authentication =(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
       LoginUser loginUser =(LoginUser) authentication.getPrincipal();
       Integer userid = loginUser.getUser().getUserId();
       //删除redis中的对应值
       redisCache.deleteObject("demo-user:"+userid);
       return ResponseMessage.success();
    }
}
